package com.chamberlain.framework.web.service;

import com.chamberlain.common.constant.Constants;
import com.chamberlain.common.core.domain.entity.SysUser;
import com.chamberlain.common.core.domain.model.LoginUser;
import com.chamberlain.common.exception.ServiceException;
import com.chamberlain.common.exception.user.UserPasswordNotMatchException;
import com.chamberlain.common.utils.DateUtils;
import com.chamberlain.common.utils.MessageUtils;
import com.chamberlain.common.utils.ip.IpUtils;
import com.chamberlain.framework.manager.AsyncManager;
import com.chamberlain.framework.manager.factory.AsyncFactory;
import com.chamberlain.framework.security.provider.HarmonyAuthenticationProvider;
import com.chamberlain.system.service.ISysUserService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author: CYY
 * @date: 2024/3/28
 */
@Component
public class HarmonyLoginService {
    @Resource
    private HarmonyAuthenticationProvider authenticationManager;

    @Resource
    private ISysUserService userService;

    @Resource
    private TokenService tokenService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String harmonyLogin(String username, String password) {
        // 用户验证
        Authentication authentication;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        return tokenService.createToken(loginUser);
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
